package com.kmxd.ams.app.jy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.kmxd.ams.client.jy.IStatisticsSvc;
import com.kmxd.ams.client.jy.dto.StatisticsAddDTO;
import com.kmxd.ams.client.jy.dto.StatisticsEditDTO;
import com.kmxd.ams.client.jy.dto.StatisticsQueryDTO;
import com.kmxd.ams.client.jy.vo.StatisticsVO;
import com.kmxd.ams.client.system.ISysUserSvc;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.core.util.IdUtil;
import com.kmxd.ams.infra.jy.entity.Statistics;
import com.kmxd.ams.infra.jy.mapper.StatisticsMapper;
import com.kmxd.ams.infra.system.entity.SysUser;
import java.util.*;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 统计信息 服务实现类
 *
 * @author ZuoLG
 * @since 2023-10-16
 */
@Service
@AllArgsConstructor
public class StatisticsSvcImpl extends ServiceImpl<StatisticsMapper, Statistics>
        implements IStatisticsSvc {
    private final ISysUserSvc sysUserSvc;

    @Override
    public List<Map<String, String>> monthStatistics(StatisticsQueryDTO req) {
        String startTime = DateUtil.format(req.getStartTime(), DatePattern.NORM_DATE_PATTERN);
        String endTime = DateUtil.format(req.getEndTime(), DatePattern.NORM_DATE_PATTERN);
        return this.baseMapper.selectMonthReport(
                req.getFilingMode(), req.getPurposeArhiving(), startTime, endTime);
    }

    @Override
    public List<Map<String, String>> yearStatistics(StatisticsQueryDTO req) {
        return this.baseMapper.selectYearReport(
                req.getFilingMode(), req.getPurposeArhiving(), req.getYear());
    }

    @Override
    public List<Map<String, Object>> evaluateReport(StatisticsQueryDTO req) {
        List<Statistics> list =
                this.baseMapper.getByCondition(
                        req.getFilingMode(), req.getPurposeArhiving(), req.getYear().toString());
        List<Map<String, Object>> returnMap = Lists.newArrayList();
        if (ObjUtil.isEmpty(list) || list.isEmpty()) {
            return returnMap;
        }
        int[] months = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        for (int month : months) {
            Map<String, Object> map = new HashMap<>();
            // 次 人次 卷次 人数 查到 未查到 部分查到 未查到 好评 中评 差评
            int timeNum = 0, manTime = 0, volNum = 0, peopleNum = 0, findNum = 0, partFindNum = 0, noFindNum = 0, goodEval = 0, inEval = 0, badEval = 0;
            List<Statistics> listData =
                    list.stream()
                            .filter(x -> ObjUtil.equal(x.getTimeMonth(), month))
                            .collect(Collectors.toList());
            for (Statistics item : listData) {
                timeNum += ObjUtil.isEmpty(item.getMainOrder()) ? 0 : item.getMainOrder();
                manTime += ObjUtil.isEmpty(item.getPersonOrder()) ? 0 : item.getPersonOrder();
                volNum += ObjUtil.isEmpty(item.getVolOrder()) ? 0 : item.getVolOrder();
                if (ObjUtil.isNotEmpty(item.getUseEval())) {
                    int useEval = item.getUseEval();
                    //利用评价  0-查到 1-部分查到 2-未查到
                    if (useEval == 0) {
                        findNum++;
                    } else if (useEval == 1) {
                        partFindNum++;
                    }
                    if (useEval == 2) {
                        noFindNum++;
                    }
                }
                if (ObjUtil.isNotEmpty(item.getServerEval())) {
                    //服务评价 5-极好 4-好 3-一般 2-差 1-极差
                    int serverEval = item.getServerEval();
                    if (serverEval == 5) {
                        goodEval++;
                    } else if (serverEval == 3) {
                        inEval++;
                    }
                    if (serverEval == 1) {
                        badEval++;
                    }
                }
            }
            map.put("month", month);
            map.put("timeNum", timeNum);
            map.put("manTime", manTime);
            map.put("volNum", volNum);
            map.put("peopleNum", timeNum * manTime);
            map.put("findNum", findNum);
            map.put("partFindNum", partFindNum);
            map.put("noFindNum", noFindNum);
            map.put("goodEval", goodEval);
            map.put("inEval", inEval);
            map.put("badEval", badEval);
            returnMap.add(map);
        }
        return returnMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(StatisticsAddDTO req) {
        if (ObjUtil.isEmpty(req.getUserId())) {
            throw BizTipException.instance(ErrorCode.VALIDATE_NOT_NULL, "操作对象不能为空！");
        }

        Statistics entity = BeanUtil.copyProperties(req, Statistics.class);
        entity.setCreateTime(DateUtil.date());
        entity.setApplyDate(DateUtil.date());
        entity.setTimeYear(DateUtil.year(entity.getCreateTime()));
        entity.setTimeMonth(DateUtil.month(entity.getCreateTime()) + 1);
        StatisticsVO statisticsVO = view(req.getUserId());
        if (ObjUtil.isNotEmpty(statisticsVO)) {
            entity.setId(statisticsVO.getId());
        }

        this.saveOrUpdate(entity);
        // 修改用户评价为已评价
        SysUser sysUser = sysUserSvc.getById(req.getUserId());
        sysUser.setUserEvaluation("1");
        sysUserSvc.updateById(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(StatisticsEditDTO req) {
        if (ObjUtil.isEmpty(req.getUserId())) {
            throw BizTipException.instance(ErrorCode.VALIDATE_NOT_NULL, "操作对象不能为空！");
        }

        Statistics entity = BeanUtil.copyProperties(req, Statistics.class);
        entity.setCreateTime(DateUtil.date());
        entity.setApplyDate(DateUtil.date());
        entity.setTimeYear(DateUtil.year(entity.getCreateTime()));
        entity.setTimeMonth(DateUtil.month(entity.getCreateTime()) + 1);
        StatisticsVO statisticsVO = view(req.getUserId());
        if (ObjUtil.isNotEmpty(statisticsVO)) {
            entity.setId(statisticsVO.getId());
        }
        this.saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(String ids) {
        Set<Long> idList = IdUtil.split(ids);
        this.baseMapper.deleteBatchIds(idList);
    }

    @Override
    public StatisticsVO view(Long id) {
        if (id == null) {
            throw BizTipException.instance(ErrorCode.VALIDATE_NOT_NULL, "操作对象不能为空！");
        }
        LambdaQueryWrapper<Statistics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Statistics::getUserId, id);
//        wrapper.eq(Statistics::getTimeMonth, DateUtil.month(DateUtil.date()) + 1);
        Statistics entity = this.list(wrapper).stream().findFirst().orElse(null);
        return ObjUtil.isEmpty(entity) ? null : BeanUtil.copyProperties(entity, StatisticsVO.class);
    }
}
